package com.xbongbong.crm.perform.query.list.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmListQryService;
import com.xbongbong.crm.handle.analysis.DefaultListAnalysisDataHandler;
import com.xbongbong.crm.service.impl.RefundLinkProductServiceImpl;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.UnitEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkDetailPojo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.parent.explain.HandleExplainHelp;
import com.xbongbong.parent.pojo.list.ConditionListPojo;
import com.xbongbong.parent.pojo.list.ConditionListResultPoJo;
import com.xbongbong.parent.pojo.list.DataAnalysisListPojo;
import com.xbongbong.parent.pojo.list.FieldListPojo;
import com.xbongbong.parent.pojo.list.PermissionListPojo;
import com.xbongbong.pro.applist.pojo.AppListPojo;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.HandleExplainPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.ListGroupEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.product.RefundProductEnum;
import com.xbongbong.saas.help.SaasLinkProductHelp;
import com.xbongbong.saas.help.SaveFormatHelp;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 退货退款列表页
 * @author 吴峰
 * @date 2022/06/13 14:43
 */
@Service("refundListServiceImpl")
@Slf4j
public class RefundListServiceImpl extends AbstractCrmListQryService {
    @Resource
    private SaasLinkProductHelp saasLinkProductHelp;
    @Resource
    private HandleExplainHelp handleExplainHelp;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private DefaultListAnalysisDataHandler defaultListAnalysisDataHandler;
    @Resource
    private RefundLinkProductServiceImpl refundLinkProductService;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private CustomerModel customerModel;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.REFUND.getCode());
    }

    @Override
    public List<ConditionsEntityExt> getPermission(PermissionListPojo permissionListPojo) throws XbbException {
        UserVO userVO = permissionListPojo.getUserVO();
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        if (userVO.isMaxDataPermission()){
            return conditionList;
        }

        return getTeamUserPermission(userVO);
    }

    @Override
    public ConditionListResultPoJo getCondition(ConditionListPojo conditionListPojo) throws XbbException {
        List<ConditionsEntityExt> list = new ArrayList<>();
        list.addAll(getCommonConditionList(conditionListPojo));
        conditionListPojo.setConditionList(list);
        // 公共筛选
        webCommonFilter(conditionListPojo);
        return new ConditionListResultPoJo(conditionListPojo.getConditionList(), conditionListPojo.getShouldConditionList());
    }



    private List<ConditionsEntityExt> getCommonConditionList(ConditionListPojo conditionListPojo) throws XbbException {
        List<ConditionsEntityExt> list = conditionListPojo.getConditionList() == null ? new ArrayList<>() : conditionListPojo.getConditionList();

        conditionListPojo.setConditionList(list);
        setCommonCondition(conditionListPojo);
        // 关联产品筛选
        saasLinkProductHelp.selectProductCondition(list, conditionListPojo.getCorpid());

        return list;
    }

    @Override
    public ConditionListResultPoJo mobileGetCondition(ConditionListPojo conditionListPojo) throws XbbException {
        //  手机端条件封装
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionListPojo.getConditionList(), conditionListPojo.getUserVO(), XbbRefTypeEnum.REFUND.getCode(), conditionListPojo.getSubBusinessType(), conditionListPojo.getPlatform());
        // 公共条件封装
        getCommonConditionList(conditionListPojo);
        return new ConditionListResultPoJo(conditionListPojo.getConditionList(), conditionListPojo.getShouldConditionList());
    }

    @Override
    public HandleExplainPojo getExplain(FieldListPojo fieldListPojo) throws XbbException {
        try {

            String corpid = fieldListPojo.getCorpid();
            Integer saasMark = fieldListPojo.getSaasMark();

            Boolean isJxcUse = paasAppModel.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);


            PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, fieldListPojo.getFormId(), fieldListPojo.getBusinessType());
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);

            // 【审批中】分组数据禁用快速编辑
            if (Objects.equals(fieldListPojo.getDefaultGroup(), 1) && Objects.equals(fieldListPojo.getListGroupId(), Long.valueOf(ListGroupEnum.APPROVAL.getCode()))) {
                explainList.forEach(item -> item.setEditable(0));
            }
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<String> fieldList = new ArrayList<>();
            // 进销存未开启时，移掉“退货状态”字段
            explainList.removeIf(item->!isJxcUse && Objects.equals(item.getAttr(), RefundEnum.REFUND_STATUS.getAttr()));
            explainList.forEach(item->{
                if (!Objects.equals(FieldTypeEnum.SUB_FORM.getType(), item.getFieldType())) {
                    fieldList.add(item.getAttr());
                }
                // saas解释处理
                if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
                    if (Objects.equals(item.getFieldType(), FieldTypeEnum.LINK_BUSINESS_SINGLE.getType())
                            || Objects.equals(item.getFieldType(), FieldTypeEnum.LINK_BUSINESS_MULTI.getType())) {
                        LinkDetailPojo linkDetail = new LinkDetailPojo();
                        linkDetail.setBusinessType(item.getLinkedType());
                        linkDetail.setSubBuisenssType(item.getLinkedType());
                        linkDetail.setSaasMark(SaasMarkEnum.SAAS.getCode());
                        item.setLinkDetail(linkDetail);
                    }
                }
                if (Objects.equals(FieldTypeEnum.SELECT_PRODUCT.getType(),item.getFieldType())){
                    SubFormPoJo subForm = item.getSubForm();
                    if (subForm != null && subForm.getItems() != null) {
                        List<? extends FieldAttrEntity> subExplainList = subForm.getItems();
                        Iterator<? extends FieldAttrEntity> iterator = subExplainList.iterator();
                        while (iterator.hasNext()){
                            FieldAttrEntity subFieldAttrEntity = iterator.next();
                            if (Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.SOURCE_DOC.getAttr())
                                    || Objects.equals(subFieldAttrEntity.getAttr(), RefundProductEnum.INSTOCK_NUM.getAttr())
                                    || Objects.equals(subFieldAttrEntity.getAttr(), RefundProductEnum.WAIT_INSTOCK_NUM.getAttr())
                                    || Objects.equals(subFieldAttrEntity.getAttr(), RefundProductEnum.BATCH.getAttr())
                                    || Objects.equals(subFieldAttrEntity.getAttr(), RefundProductEnum.GUARANTEE_PERIOD.getAttr())
                                    || Objects.equals(subFieldAttrEntity.getAttr(), RefundProductEnum.PRODUCE_DATE.getAttr())
                                    || Objects.equals(subFieldAttrEntity.getAttr(), RefundProductEnum.EXPIRE_DATE.getAttr())) {
                                iterator.remove();
                                continue;
                            }
                            if (Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.PRODUCT.getAttr())){
                                subFieldAttrEntity.setFieldType(FieldTypeEnum.TEXT.getType());
                                break;
                            }
                        }
                    }
                }
                explainMap.put(item.getAttr(), item);
            });
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO(explainList, fieldListPojo.getForm(), fieldListPojo.getCorpid(), fieldListPojo.getUserVO().getUserId(), fieldListPojo.getUserVO(), true, fieldListPojo.getSubBusinessType());
            HandlerExplainVO handlerExplainVO = handleExplainHelp.handleExplain(handlerExplainDTO);
            HandleExplainPojo handleExplainPojo = new HandleExplainPojo();
            explainList = handlerExplainVO.getHeadList();
            handleExplainPojo.setFieldList(fieldList);
            handleExplainPojo.setExplainList(explainList);
            return handleExplainPojo;
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            log.error("com.xbongbong.crm.perform.query.list.impl.RefundListServiceImpl.getExplain error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public List<PaasFormDataEntityExt> webDataAnalysis(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {
        List<PaasFormDataEntityExt> formDataList = dataAnalysisListPojo.getFormDataList();

        FormDataListDTO formDataListDTO = new FormDataListDTO(dataAnalysisListPojo.getCorpid(), dataAnalysisListPojo.getFormId(), dataAnalysisListPojo.getSaasMark(), dataAnalysisListPojo.getBusinessType(), dataAnalysisListPojo.getSubBusinessType(), dataAnalysisListPojo.getDistributorMark(), dataAnalysisListPojo.getUserVO(), dataAnalysisListPojo.getAnalysisAmountOfThousandBitsWithOriginalValue());
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        formDataListVO.setPaasFormDataESList(formDataList);
        List<FieldAttrEntity> explainList = dataAnalysisListPojo.getExplainList();
        formDataListVO.setHeadList(explainList);
        // 解析关联产品，只有web需要
        refundLinkProductService.analysisListProductData(formDataListDTO, formDataListVO.getPaasFormDataESList(), formDataListVO.getHeadList(), 1, null);
        defaultListAnalysisDataHandler.analysisDataList(formDataListDTO, formDataListVO);
        defaultListAnalysisDataHandler.analysisAmountOfThousandBits(formDataListVO, dataAnalysisListPojo.getAnalysisAmountOfThousandBitsWithOriginalValue());

        return formDataListVO.getPaasFormDataESList();
    }


    @Override
    public List<AppListPojo> dingtalkOperate(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {
        // 关联客户
        Map<Long, String> cusIdAndName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> dataIdList = new ArrayList<>();
        List<PaasFormDataEntityExt> esEntities = dataAnalysisListPojo.getFormDataList();
        esEntities.forEach(item -> {
            JSONObject itemData = item.getData();
            try {
                SaveFormatHelp.formatLinkBusiness4Save(itemData, RefundEnum.CUSTOMER_ID.getAttr(), RefundEnum.CUSTOMER_ID_LINKED_TEXT.getAttr(), RefundEnum.CONTRACT_ID_LINKED_TEXT.getFieldType());
            } catch (XbbException e) {
                e.printStackTrace();
            }
            try {
                dataIdList.add(FastJsonHelper.getLongOrDefaultFromFormData(itemData, RefundEnum.CUSTOMER_ID.getAttr(),0L));
            } catch (XbbException e) {
                e.printStackTrace();
            }
        });
        String corpid = dataAnalysisListPojo.getCorpid();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("ids", dataIdList);
        List<CustomerEntityExt> cusExt = customerModel.findEntitys(param);
        cusExt.forEach(item -> cusIdAndName.put(item.getId(), item.getData().getString(CustomerManagementEnum.NAME.getAttr())));

        List<AppListPojo> appListPojos = new ArrayList<>();
        for (PaasFormDataEntityExt refund : esEntities) {
            JSONObject data = refund.getData();
            Long refundId = refund.getDataId();

            // 签订人
            String signUser = FastJsonHelper.getStringOrDefaultFromFormData(data, RefundEnum.SIGN_USER.getAttr(), "");
            Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(data, RefundEnum.CUSTOMER_ID.getAttr(),0L);

            JSONObject superScript = new JSONObject();
            JSONObject others = new JSONObject();

            Long time = data.getLongValue(RefundEnum.SIGN_DATE.getAttr());

            //其他
            others.put("serialNo", refund.getSerialNo());
            // 退货金额
            String amount = StringUtil.formatDouble(data.getDoubleValue(RefundEnum.RETURN_AMOUNT.getAttr()));
            others.put("amount", amount + UnitEnum.MONEY.getName());



            List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
            if (titleList.isEmpty()) {
                FormTitlePoJo titlePoJo = new FormTitlePoJo();
                titlePoJo.setValue(Collections.singletonList(refund.getSerialNo()));
                titleList.add(titlePoJo);
            }

            //app系统关联数据展示需要 others 和 superScript
            data.put("others",others);
            data.put("superScript",superScript);
            appListPojos.add(new AppListPojo(refundId, titleList, summaryList, superScript, lablesList, others));
            JSONObject sourceData = refund.getSourceData();
            if (data.containsKey(RefundEnum.CUSTOMER_ID.getAttr()) && sourceData.containsKey(RefundEnum.CUSTOMER_ID.getAttr())) {
                data.put(RefundEnum.CUSTOMER_ID.getAttr(), sourceData.get(RefundEnum.CUSTOMER_ID.getAttr()));
            }
        }

        return appListPojos;
    }

    @Override
    public void webOperate(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {

    }
}
